package com.xiaoshuidi.cloud.framework.systemevent.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.function.Consumer;

public class LeaseSystemEventConsumer implements Consumer<LeaseSystemEvent>, ApplicationContextAware {
    private List<LeaseSystemEventListener> listeners;
    private ObjectMapper objectMapper;

    public LeaseSystemEventConsumer(List<LeaseSystemEventListener> listeners, ObjectMapper objectMapper) {
        this.listeners = listeners;
        this.objectMapper = objectMapper;
    }

    @Override
    public final void accept(LeaseSystemEvent event) {
        if (CollectionUtils.isEmpty(listeners)) {
            return;
        }
        for (LeaseSystemEventListener listener : listeners) {
            if (listener.getEventType().name().equals(event.getEventType())) {
                listener.onEvent(objectMapper.convertValue(event.getData(), listener.getEventType().getEventDataClass()));
            }
        }
    }

    private ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
